import T from 'ant-design-vue/es/table/Table'
import request from '@/utils/request'
import notification from 'ant-design-vue/es/notification'
import LQueryForm from '@/components/lt/form/LQueryForm'
import {StringToJson,isJSON} from '@/utils/util'

let defaultPageSize = 15
//默认分页
const ipagination = {
    current: 1,
    pageSize: defaultPageSize,
    pageSizeOptions: ['15','20', '30', '40'],
    showTotal: (total, range) => {
        return range[0] + "-" + range[1] + " 共" + total + "条"
    },
    showQuickJumper: false,
    showSizeChanger: true,
    total: 0
}



export default {
    name:'EchTable',
    components:{
        LQueryForm
    },
    data(){
        return{
             /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
            queryParam: [],
            orderColumns:[],
            selectedRows: [],
            selectedRowKeys:[],

            /**以下定义的是为了后面替换TABLE组件中的原始PROPS */
            localLoading: false,
            localDataSource:[],
            lastSorter:{},
            localPagination: Object.assign({}, ipagination),
            localHttpRequest:null,//自定义请求
            //查询框的值
            queryFormVal:{},
            dataCenter:{
                pageNo:1,
                pageSize:defaultPageSize,
                orderColumns:[],
                queryForm:[],
            },
            localInitQuery:null
        
        }
    },
    props:Object.assign({},T.props,{
        httpRequest:Function,
        formAttributes:{
            type:Array,
            default:()=>[]
        },
        initQuery:{
            type:[String,Array],
            default:()=>''
        },
        initOrder:{
            type:[String,Array],
            default:()=>''
        },
        axiosUrl:{
            type:String,
            required:false
        },
        axiosMethod:{
            type:String,
            default:'post'
        },
        showPagination: {
            type: Boolean,
            default: true
        },
        showQueryForm: {
            type: Boolean,
            default: true
        },
        rowSelection: {
            type: [Object,String],
            default: null
        },
        pageSize:Number,
        isAutoLoad:{//是否自动查询
            type:Boolean,
            default:true
        },
        componentRef:[String,Number],
        entityClassName:String,
          
    }),
    watch:{
        initQuery: {
            deep: true,
            handler(newV, oldV) {
                if(isJSON(newV)){
                    this.localInitQuery=this.StringToJson(newV)
                }
                
            }
        },
        
    },
    created(){
        /*
        if(isJSON(this.initQuery)){
            this.localInitQuery = this.StringToJson(this.initQuery)
        }
        
        this.localHttpRequest=request;
        if(this.httpRequest){
            this.localHttpRequest=this.httpRequest;
        }
        if(this.pageSize){
            this.localPagination.pageSize=this.pageSize
            ipagination.pageSize=this.pageSize
        }

        if(this.showPagination){
            this.localPagination = Object.assign({}, this.localPagination, ipagination)
        }else{
            this.localPagination = false
        }
  
        if(this.isAutoLoad){
            this.searchQuery()
        }
     */
     
        
    },
    methods:{
      
        /**
         * 查询方法
         */
        searchQuery(){
            if(this.localPagination){
                if(this.pageSize){
                    this.localPagination.pageSize=this.pageSize
                    ipagination.pageSize=this.pageSize
                }else{
                    this.localPagination.pageSize=defaultPageSize
                    ipagination.pageSize=defaultPageSize
                }
            }
            
            //点击查询，重新回到第一页
            this.localPagination = Object.assign({}, {
                showTotal:ipagination.showTotal ,
                current: ipagination.current, 
                pageSize: this.localPagination.pageSize || ipagination.pageSize,
                pageSizeOptions:this.localPagination.pageSizeOptions || ipagination.pageSizeOptions
            })
           
            //清除上次遗留的排序信息
            this.lastSorter ={}
            this.localDataSource=[]
            this.loadData()
        },
        refresh(){
            //刷新，重新查询数据
            this.loadData()
        },
        refreshData(){
            //重新加载当前数据，不进行查询,为了回显更新过的数据
            if(this.localDataSource && this.localDataSource.length>0){
                let dataSource = Object.assign([], this.localDataSource);
                this.localDataSource = dataSource
            }
        },
        /**
         * 请求后台
         * @param {*} pagination 
         * @param {*} filters 
         * @param {*} sorter 
         */
        loadData(pagination, filters, sorter) {
            let that = this;
            if(!that.axiosUrl){
                // that.$message.error("请设置请求地址:axiosUrl属性!")
                return
            }
            //  console.log(that.dataCenter)
            that.localLoading=true
            that.getQueryParams(pagination, filters, sorter);
            that.localHttpRequest({url: that.axiosUrl,method: that.axiosMethod,data:that.dataCenter}).then(r=>{
                if(r.success){
                    that.localDataSource=r.result.records || r.result
                    that.localLoading=false
                    if(that.showPagination){
                        let current = 1
                        let total =  0
                        if(r.result){
                            if(r.result.current){
                                current = r.result.current
                            }
                            if(r.result.total){
                                total = r.result.total
                            }
                            if(r.result.records){
                                if(r.result.records.current){
                                    current = r.result.records.current
                                }
                                if (r.result.records.total){
                                    total = r.result.records.total
                                }
                            }
                        }
                        that.localPagination =  Object.assign({}, that.localPagination, {
                            current: current, // 返回结果中的当前分页数
                            total: total, // 返回结果中的总记录数
                            showSizeChanger: ipagination.showSizeChanger,
                            pageSize: (pagination && pagination.pageSize) || that.localPagination.pageSize
                        })
                    }else{
                        that.localPagination = false
                    }
                    //查询成功以后执行回调
                    this.$emit('handleLoad',that);
                }else{
                    that.localLoading=false
                    notification.error({ message: '系统提示', description: r.message || "执行出现错误"}) 
                }
                
                
            }).catch(function (error) {
                that.localLoading=false;
              //  notification.error({ message: '系统提示', description: error+""})
            })
            
        },
        
        /**
         * 组装查询参数
         * @param {*} pagination 
         * @param {*} filters 
         * @param {*} sorter 
         */
        getQueryParams(pagination, filters, sorter){
            let that = this;
            that.queryParam=[]
            that.orderColumns=[]
            let queryParamField=[]//临时存放QUERYFORM字段信息
            let queryAttributes={}
            let betweenItem={} //存放范围查询的字段
            let stSign="_st"
            let etSign="_et"
            if(that.formAttributes && that.formAttributes.length>0){
                //这里手动赋值，是因为在外部调用表格的searchQuery方法而不是点击查询按钮，会出现无法获取查询框值的问题
                if(that.$refs["LQueryForm"]){
                    that.queryFormVal = that.$refs["LQueryForm"].getQueryFormVal()
                }

                that.formAttributes.forEach(item=>{
                    queryAttributes[item['field']] = item
                    if(item['condition']=='between'){
                        betweenItem[item['field']+stSign] = {field:item['field'],condition:'ge'}
                        betweenItem[item['field']+etSign] = {field:item['field'],condition:'le'}
                    }
        
                })
                for(let key in that.queryFormVal){
                    if(that.queryFormVal[key]){
                        if(betweenItem[key] && that.queryFormVal[key]){
                            //如果有范围查询，并且有值
                            betweenItem[key]['val']=that.queryFormVal[key]
                            that.queryParam.push(betweenItem[key])
                            queryParamField.push(betweenItem[key]['field'])
                            continue
                        }

                        queryAttributes[key]['val']=that.queryFormVal[key]
                        that.queryParam.push(queryAttributes[key]) 
                        queryParamField.push(key)
                    }
                
                }
            }
            
            
            //默认查询放到最后并过滤掉重复的查询条件
            if(that.localInitQuery && that.localInitQuery.length>0){
                that.localInitQuery.forEach(v=>{
                    if(queryParamField.length==0?true:!queryParamField.includes(v['field'])){
                        that.queryParam.push(v)
                    } 
                })
            }
            //增加排序功能，支持单列排序,如果单机某列排序，则默认排序不起作用
            if(sorter && sorter.order){
                that.lastSorter = sorter
                that.orderColumns.push({"field":sorter.field,"val":sorter.order})
            }else if(that.lastSorter && that.lastSorter.order ){
                that.orderColumns.push({"field":that.lastSorter.field,"val":that.lastSorter.order})
            }else {
                //默认的排序放到最后并过滤掉重复的排序条件
                if(isJSON(this.initOrder)){
                    if(that.StringToJson(that.initOrder) && this.StringToJson(that.initOrder).length>0){
                        that.StringToJson(that.initOrder).forEach(v=>{
                            if(v['val'] && (!sorter?true:v['field']!=sorter.field)){
                                that.orderColumns.push(v)
                            } 
                        })
                    }
                }
                
            }
            that.dataCenter.orderColumns=that.orderColumns;
            that.dataCenter.queryForm=that.queryParam;
            that.dataCenter.pageNo = (pagination && pagination.current) || (that.showPagination && that.localPagination.current) || ipagination.current
            that.dataCenter.pageSize = (pagination && pagination.pageSize) || (that.showPagination && that.localPagination.pageSize) || ipagination.pageSize
            that.dataCenter.entityClassName=that.entityClassName
        },
        
        /**
         * 批量加载下拉数据源信息，多个用,隔开
         */
        
        onQueryFormChange(item){
            this.$emit("onQueryFormChange",item)
        },
        getDataCenter(){
            return this.dataCenter
        },
        setInitQuery(initQuery){
            this.localInitQuery = this.StringToJson(initQuery)
        },
        StringToJson(str){
            if(str){
              str =  StringToJson(str)
            }
            return str
        },
        
    },
    render(){
        const props = {}
        const localKeys = Object.keys(this.$data)
        Object.keys(T.props).forEach(k=>{
            
            //用本地的属性替代默认属性，因为VUE子组件不能修改由父组件传递过来的值，
            const localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
            if (localKeys.includes(localKey)) {
                props[k] = this[localKey]
                return props[k]
            }
            if (k === 'rowSelection') {
                if(this.rowSelection){
                    props[k] = {
                        ...this.rowSelection,
                        selectedRows: this.selectedRows,
                        selectedRowKeys: this.selectedRowKeys,
                        onChange: (selectedRowKeys, selectedRows) => {
                          
                            this.selectedRowKeys = selectedRowKeys;
                            this.selectedRows=selectedRows
                            typeof this[k].onChange !== 'undefined' && this[k].onChange(selectedRowKeys, selectedRows)
                        }
                    }
                    return props[k]
                }else{
                    props[k] = null
                    return props[k]
                }
                
            }
            props[k]=this[k]
            return props[k]
        })
    
        
        const table=(
            <a-table  ref={this.componentRef} {...{ props, scopedSlots: { ...this.$scopedSlots }}} onChange={this.loadData} onExpand={ (expanded, record) => { this.$emit('expand', expanded, record) } }>
                { Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>)) }
            </a-table>
        )
        const queryForm=(
            <LQueryForm ref="LQueryForm" queryTable={this} formAttributes={this.formAttributes}></LQueryForm>
        )
        return(
            <div>
               {this.$slots.default}
               {this.showQueryForm?queryForm:null}
               {table}
            </div>
        )
    }

}